package cn.cdutetc.foxwatch.controller.user;

import cn.cdutetc.foxwatch.exception.MyException;
import cn.cdutetc.foxwatch.pojo.DemoPojo;
import cn.cdutetc.foxwatch.pojo.Result;
import cn.cdutetc.foxwatch.pojo.UserInfo;
import cn.cdutetc.foxwatch.serveice.UserInfoService;
import cn.cdutetc.foxwatch.utils.ThreadLocalUtil;
import io.micrometer.common.util.StringUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Tag(name = "用户信息相关接口", description = "用户信息相关接口")
public class UserInfoController {
    @Autowired
    private UserInfoService userService;

    @Operation(description = "用户注册-用户名、密码、确认密码")
    @PostMapping("/register")
    public Result<String> register(@RequestBody UserInfo user) throws Exception {
        System.out.println(user.toString());
        Boolean i = userService.register(user);
        return i ? Result.success() : Result.error("注册失败");
    }

    @Operation(description = "用户登录-用户名、密码")
    @PostMapping("/login")
    public Result<Map<String, String>> login(@RequestBody UserInfo user) throws MyException {
        System.out.println(user.toString());
        String token = userService.login(user);
        Map<String, String> result = new HashMap<>();
        result.put("token", token);
        return StringUtils.isEmpty(token) ? Result.error("登录失败") : Result.success(result);
    }

    @Operation(description = "根据用户id获取用户信息")
    @GetMapping("/getUserInfo/{id}")
    public Result<UserInfo> getUserInfoById(@PathVariable("id") Integer userId) throws Throwable {
        if (userId == null) {
            throw new Throwable("userId is null");
        }
        UserInfo user = userService.getById(userId);
        return Result.success(user);
    }

    @Operation(description = "获取当前用户信息")
    @GetMapping("/getInfo")
    public Result<UserInfo> getUserInfoById()  {
        HashMap<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("userId");
        UserInfo user = userService.getById(userId);
        return Result.success(user);
    }
    @PutMapping("/put")
    @Operation(description = "修改用户信息")
    public Result<String> put(@RequestBody UserInfo user) {
        HashMap<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("userId");
        user.setId(userId);
        boolean b = userService.updateById(user);
        return b ? Result.success() : Result.error("设置失败");
    }

}
